package com.linkage.educloud.ah.view.fragment.login;

import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.linkage.educloud.ah.R;
import com.linkage.educloud.ah.adapter.MyAccountPopWindowAdapter;
import com.linkage.educloud.ah.bean.AccountData;
import com.linkage.educloud.ah.mvp.ABasicPresenter;
import com.linkage.educloud.ah.mvp.contract.ILoginContract;
import com.linkage.educloud.ah.mvp.presenter.LoginPresenter;
import com.linkage.educloud.ah.util.ImageLoader;
import com.linkage.educloud.ah.view.BasicTitleFragment;
import com.linkage.educloud.ah.view.activity.MainActivity;
import com.zzhou.common.library.util.LogUtils;
import com.zzhou.common.library.util.NativeHelper;
import com.zzhou.common.library.util.StringUtil;
import com.zzhou.common.library.util.ToastShow;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * <desc>
 * Created by The Moss on 2018/8/20.
 */

public class LoginFragment extends BasicTitleFragment implements ILoginContract.IView {


    @BindView(R.id.fragment_login_avatar)
    CircleImageView mAvatarImage;
    @BindView(R.id.fragment_login_accountEdit)
    EditText mAccountEdit;
    @BindView(R.id.fragment_login_downImage)
    ImageView mDownImage;
    @BindView(R.id.fragment_login_pass_iconImage)
    ImageView mPassIconImage;
    @BindView(R.id.fragment_login_passwordEidt)
    EditText mPasswordEidt;
    @BindView(R.id.fragment_login_eyeImage)
    ImageView mEyeImage;
    @BindView(R.id.fragment_login_smsCodeBtn)
    Button mSmsCodeBtn;
    @BindView(R.id.fragment_login_passwordRl)
    RelativeLayout mPasswordRl;
    @BindView(R.id.fragment_login_smsText)
    TextView mSmsText;
    @BindView(R.id.fragment_login_getPassText)
    TextView mGetPassText;
    @BindView(R.id.fragment_login_downRl)
    RelativeLayout mDownRl;
    @BindView(R.id.fragment_login_btn)
    Button mLoginBtn;

    PopupWindow mPopupWindow;

    ILoginContract.IPresenter iPresenter;
    int loginWay = 0;//登录方式 1为验证码登录，默认密码登录
    private boolean isEyes;

    public static LoginFragment newInstance() {
        return new LoginFragment();
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_login;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        iPresenter = new LoginPresenter(getActivity(), this);
        initView(iPresenter);
    }

    @Override
    protected void initView(ABasicPresenter iaPresenter) {
        super.initView(iaPresenter);
        iPresenter.getLastLoginAccounts();
        onValidateResult(false, null);
        mAccountEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String input = s.toString();
                onValidateResult(false, null);
                iPresenter.valudateAccountLocal(input);
            }
        });
    }

    @OnClick({R.id.fragment_login_downImage, R.id.fragment_login_eyeImage, R.id.fragment_login_smsCodeBtn,
            R.id.fragment_login_smsText, R.id.fragment_login_getPassText, R.id.fragment_login_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fragment_login_downImage://点击账号下拉
                if (mPopupWindow != null) {
                    if (!mPopupWindow.isShowing()) {
                        mPopupWindow.showAsDropDown(mDownImage);
                    } else {
                        mPopupWindow.dismiss();
                    }
                }
                break;
            case R.id.fragment_login_eyeImage://点击密码*号显示
                setPassEyes();
                break;
            case R.id.fragment_login_smsCodeBtn://获取验证码按钮
                if (StringUtil.isPhoneNumber(mAccountEdit.getText().toString())) {
                    showZloading();
                    mSmsCodeBtn.setEnabled(false);
                    iPresenter.sendSmsCode(mAccountEdit.getText().toString());
                } else {
                    ToastShow.show(getActivity(), "手机号码不正确");
                }
                break;
            case R.id.fragment_login_smsText://切换密码、验证码登录
                loginWay = 1 ^ loginWay;
                switchLoginWay(loginWay);
                break;
            case R.id.fragment_login_getPassText://获取密码按钮
                break;
            case R.id.fragment_login_btn:
                Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
                String input = mAccountEdit.getText().toString();
                if (StringUtil.isNullOrEmpty(input) || input.length() < 6 || input.length() > 11) {
                    mAccountEdit.setError("账号为6-11位");
                    mAccountEdit.startAnimation(shake);
                    return;
                }
                if (mPasswordRl.getVisibility() == View.VISIBLE) {
                    String pass = mPasswordEidt.getText().toString();
                    if (loginWay == 1) {
                        if (!StringUtil.isNumeric(pass) && pass.length() != 6) {
                            mPasswordEidt.setError("验证码6位数字");
                            mPasswordEidt.startAnimation(shake);
                            return;
                        }
                    } else {
                        if (StringUtil.isNullOrEmpty(pass) || pass.length() < 4 || pass.length() > 16) {
                            mPasswordEidt.setError("密码为4-16位");
                            mPasswordEidt.startAnimation(shake);
                            return;
                        }
                    }
                    showZloading();
                    mLoginBtn.setEnabled(false);
                    /*登录*/
                    iPresenter.login(mAccountEdit.getText().toString()
                            , NativeHelper.MD5(mPasswordEidt.getText().toString()), loginWay);
                } else {
                    /*验证*/
                    showZloading();
                    iPresenter.validateAccount(input);
                }
                break;
        }
    }

    /**
     * 切换登录方式，1验证码登录，默认密码登录
     *
     * @param way
     */
    private void switchLoginWay(int way) {
        loginWay = way;
        switch (way) {
            case 1:
                mSmsText.setText("密码登录");
                mPassIconImage.setImageResource(R.mipmap.ic_smsbox_tv);
                mPasswordEidt.setText("");
                mPasswordEidt.setHint(R.string.login_smscode_hint);
                mEyeImage.setVisibility(View.GONE);
                mSmsCodeBtn.setVisibility(View.VISIBLE);
                mGetPassText.setVisibility(View.GONE);
                break;
            default:
                mSmsText.setText("验证码登录");
                mPassIconImage.setImageResource(R.mipmap.ic_lock_tv);
                mPasswordEidt.setText("");
                mPasswordEidt.setHint(R.string.login_pass_hint);
                mEyeImage.setVisibility(View.VISIBLE);
                mSmsCodeBtn.setVisibility(View.GONE);
                mGetPassText.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void setPassEyes() {
        if (isEyes = !isEyes) {
            mEyeImage.setImageResource(R.mipmap.ic_eye_open);
            mPasswordEidt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            mEyeImage.setImageResource(R.mipmap.ic_eye_close);
            mPasswordEidt.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        mPasswordEidt.setSelection(mPasswordEidt.getText().length());
    }

    /**
     * 验证码倒计时
     */
    private void showSmsCode() {
        final long count = 60; // 设置60秒
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(count + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(@NonNull Long aLong) throws Exception {
                        return count - aLong; // 由于是倒计时，需要将倒计时的数字反过来
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        mSmsCodeBtn.setEnabled(false);
                    }
                })
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Long aLong) {
                        mSmsCodeBtn.setText(aLong + "秒后重发");
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        mSmsCodeBtn.setEnabled(true);
                        mSmsCodeBtn.setText("发送验证码");
                    }
                });
    }

    @Override
    public void onLoginResult(boolean isSuccess, Object o) {
        hideZloading();
        if (isSuccess) {
            MainActivity.launch(getActivity());
            getActivity().finish();
        } else {
            mLoginBtn.setEnabled(true);
            ToastShow.show(getActivity(), o.toString());
        }
    }

    @Override
    public void onValidateResult(boolean isSuccess, Object t) {
        hideZloading();
        if (!isSuccess && mPasswordRl.getVisibility() == View.GONE) {
            return;
        }
        if (isSuccess && mPasswordRl.getVisibility() == View.VISIBLE) {
            return;
        }
        if (!isSuccess) {
            mPasswordRl.setVisibility(View.GONE);
            mDownRl.setVisibility(View.GONE);
            mLoginBtn.setText("下一步");
            switchLoginWay(0);
        } else {
            mPasswordRl.setVisibility(View.VISIBLE);
            mDownRl.setVisibility(View.VISIBLE);
            mLoginBtn.setText("登\t录");
        }
    }

    @Override
    public void getLastLoginAccount(AccountData accountData) {
        if (accountData == null) {
            LogUtils.d("getLastLoginAccount = null");
            return;
        }
        ImageLoader.loadAvatar(getActivity(), accountData.getAvatar(), mAvatarImage);
        mAccountEdit.setText(accountData.getLoginAccount());
        mAccountEdit.setSelection(accountData.getLoginAccount().length());
        LogUtils.d("getLastLoginAccount = " + accountData.toString());
    }

    @Override
    public void getLastLoginAccounts(final List<AccountData> accounts) {
        if (accounts == null || accounts.size() == 0) {
            LogUtils.d("getLastLoginAccounts = null");
            mDownImage.setVisibility(View.GONE);
            return;
        }
        LogUtils.d("getLastLoginAccounts = " + accounts.size());
        mDownImage.setVisibility(View.VISIBLE);
        if (mPopupWindow == null) {
            mPopupWindow = new PopupWindow(getActivity());
            mPopupWindow.setAnimationStyle(R.style.MyDialogStyleTop);
            mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            // 设置弹出窗体可点击
            mPopupWindow.setTouchable(true);
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_history_account_layout, null);
            ListView listView = view.findViewById(R.id.popup_listview);
            final MyAccountPopWindowAdapter adapter = new MyAccountPopWindowAdapter(getActivity());
            adapter.setDatas(accounts);
            listView.setAdapter(adapter);
            adapter.setOnclickListener(new MyAccountPopWindowAdapter.PopWindonItemListener() {
                @Override
                public void onClickItem(int position) {
                    getLastLoginAccount(accounts.get(position));
                    mPopupWindow.dismiss();
                }

                @Override
                public void onClickDelete(int position) {
                    if (adapter.getCount() == 0) {
                        mDownImage.setVisibility(View.GONE);
                        mPopupWindow.dismiss();
                    }
                }
            });
            mPopupWindow.setContentView(view);
        }
    }

    @Override
    public void getAccountByInput(AccountData accountData) {
        if (accountData != null && !StringUtil.isNullOrEmpty(accountData.getAvatar())) {
            ImageLoader.loadAvatar(getActivity(), accountData.getAvatar(), mAvatarImage);
        } else {
            ImageLoader.loadAvatar(getActivity(), "", mAvatarImage);
        }
    }

    @Override
    public void onSendSmsCodeResult(boolean isSuccess) {
        hideZloading();
        if (isSuccess) {
            showSmsCode();
        } else {
            mSmsCodeBtn.setEnabled(true);
        }
    }

    @Override
    public boolean onBackPressed() {
        fragmentTransaction.replace(R.id.fragment_content, new RegisterFragment(), "register")
                .addToBackStack(RegisterFragment.class.getSimpleName())
                .commit();
        return true;
    }
}
